package fatworm.query.expression;

import fatworm.query.Plan;
import fatworm.query.Scan;
import fatworm.query.constant.Constant;
import fatworm.storage.table.Schema;

public class InTerm implements Term {
	
	private Expression lexp, rexp;
	
	public InTerm(Expression lexp, Expression rexp) {
		this.lexp = lexp;
		this.rexp = rexp;
	}
	
	public boolean isOK(Scan s) {
		Plan p = rexp.asSubquery();
		Scan subs = p.open();
		Constant c = lexp.evaluate(s);
		String name = null;
		
		for (String str : p.getSchema().fields())
			name = str;
		
		subs.beforeFirst();
		while (subs.next()) 
			if (c.equals(subs.getVal(name)))
				return true;
		
		return false;
	}
	
	public boolean isIn(Schema sch) {
		return lexp.isIn(sch) && rexp.isIn(sch);
	}
	
	public int reductionFactor(Plan p) {
		return p.recordsOutput() / rexp.asSubquery().recordsOutput();
	}
	
	public String toString() {
		return lexp.toString() + " IN " + rexp.toString();
	}
}